<template>
  <div class="ve-container">
    <div class="header">
      <div class="filters">
        <button 
          :class="['filter-button', { active: filterStatus === 'all' }]"
          @click="filterStatus = 'all'"
        >
          全部
        </button>
        <button 
          :class="['filter-button', { active: filterStatus === 'pending' }]"
          @click="filterStatus = 'pending'"
        >
          待审核
        </button>
        <button 
          :class="['filter-button', { active: filterStatus === 'approved' }]"
          @click="filterStatus = 'approved'"
        >
          已通过
        </button>
        <button 
          :class="['filter-button', { active: filterStatus === 'rejected' }]"
          @click="filterStatus = 'rejected'"
        >
          已拒绝
        </button>
      </div>
      <button class="back-button" @click="goBack">返回活动列表</button>
    </div>
    
    <!-- 加载状态 -->
    <div v-if="loading" class="loading">
      数据加载中...
    </div>
    
    <!-- 错误状态 -->
    <div v-else-if="error" class="error">
      {{ error }}
    </div>
    
    <!-- 数据展示 -->
    <div v-else class="content">
      <div v-if="enrollments.length === 0" class="no-data">
        暂无报名信息
      </div>
      
      <div v-else>
        <div class="info-section">
          <h3>活动信息&nbsp;&nbsp;与&nbsp;&nbsp;报名列表</h3>
          <div class="activity-info">
            <p><strong>活动名称:</strong> {{ activityInfo?.title }}</p>
            <p><strong>活动地点:</strong> {{ activityInfo?.location }}</p>
            <p><strong>活动时间:</strong> {{ formatDate(activityInfo?.startTime) }} - {{ formatDate(activityInfo?.endTime) }}</p>
          </div>
        </div>
        
        <div class="enrollments-list">
          <div class="table-container">
            <table class="enrollments-table">
              <thead>
                <tr>
                  <th>编号</th>
                  <th>姓名</th>
                  <th>联系方式</th>
                  <th>所在学院</th>
                  <th>报名时间</th>
                  <th>状态</th>
                  <th>操作</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="enrollment in filteredEnrollments" :key="enrollment.enrollId">
                  <td>{{ enrollment.enrollId }}</td>
                  <td>{{ getVolunteerInfo(enrollment.volunteerId)?.name || '未知' }}</td>
                  <td>{{ getVolunteerInfo(enrollment.volunteerId)?.phone || '未知' }}</td>
                  <td>{{ getVolunteerInfo(enrollment.volunteerId)?.department || '未知' }}</td>
                  <td>{{ formatDate(enrollment.enrollTime) }}</td>
                  <td>
                    <span :class="getStatusClass(enrollment.enrollStatus)">
                      {{ getStatusText(enrollment.enrollStatus) }}
                    </span>
                  </td>
                  <td>
                    <button 
                      v-if="enrollment.enrollStatus === 0" 
                      class="approve-button"
                      @click="approveEnrollment(enrollment.enrollId)"
                    >
                      通过
                    </button>
                    <button 
                      v-if="enrollment.enrollStatus === 0" 
                      class="reject-button"
                      @click="rejectEnrollment(enrollment.enrollId)"
                    >
                      拒绝
                    </button>
                    <button 
                      v-if="enrollment.enrollStatus === 1" 
                      class="cancel-button"
                      @click="cancelEnrollment(enrollment.enrollId)"
                    >
                      取消通过
                    </button>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { useRoute } from 'vue-router'

// 定义 props
const props = defineProps({
  activityId: {
    type: Number,
    required: false
  }
})

// 定义报名信息结构
interface Enrollment {
  enrollId: number
  volunteerId: number
  activityId: number
  enrollTime: string
  enrollStatus: number // 0-待审核, 1-已通过, 2-已拒绝
  auditTime: string | null
  auditUserId: number | null
  reason: string | null
}

// 定义志愿者信息结构
interface Volunteer {
  volunteerID: string
  userID: string
  name: string
  phone: string
  email: string
  department: string
  position: string
  experience: string
  status: string
  applyTime: string
  reviewNotes: string | null
}

// 定义活动信息结构
interface Activity {
  activityId: number
  title: string
  description: string
  startTime: string
  endTime: string
  location: string
  recruitNum: number
  recruitedNum: number
  status: number
  publishTime: string
  publisherId: number
  remark: string
}

// 响应式数据
const enrollments = ref<Enrollment[]>([])
const volunteers = ref<Record<string, Volunteer>>({})
const activityInfo = ref<Activity | null>(null)
const loading = ref(true)
const error = ref<string | null>(null)
const activityId = ref<number | null>(null)
const filterStatus = ref<'all' | 'pending' | 'approved' | 'rejected'>('all')

// 计算属性：排序后的报名列表
const sortedEnrollments = computed(() => {
  return [...enrollments.value].sort((a, b) => {
    // 待审核的条目放在最上面
    if (a.enrollStatus === 0 && b.enrollStatus !== 0) return -1
    if (b.enrollStatus === 0 && a.enrollStatus !== 0) return 1
    
    // 已拒绝的条目放在最后
    if (a.enrollStatus === 2 && b.enrollStatus !== 2) return 1
    if (b.enrollStatus === 2 && a.enrollStatus !== 2) return -1
    
    // 相同状态按报名时间排序（最新的在前）
    return new Date(b.enrollTime).getTime() - new Date(a.enrollTime).getTime()
  })
})

// 计算属性：筛选后的报名列表
const filteredEnrollments = computed(() => {
  if (filterStatus.value === 'all') {
    return sortedEnrollments.value
  }
  
  let statusValue = 0
  switch (filterStatus.value) {
    case 'pending':
      statusValue = 0
      break
    case 'approved':
      statusValue = 1
      break
    case 'rejected':
      statusValue = 2
      break
  }
  
  return sortedEnrollments.value.filter(enrollment => enrollment.enrollStatus === statusValue)
})

// 获取路由参数
const route = useRoute()

// 组件挂载时获取数据
onMounted(() => {
  // 从props、路由参数获取活动ID
  const id = props.activityId || (route.query.activityId ? Number(route.query.activityId) : null)
  if (id) {
    activityId.value = id
    fetchEnrollments(id)
    fetchActivityInfo(id)
  } else {
    error.value = '未提供活动ID'
    loading.value = false
  }
})

// 获取报名信息
const fetchEnrollments = async (id: number) => {
  try {
    loading.value = true
    const token = localStorage.getItem('token')
    
    const response = await fetch(`http://localhost:8080/ve/byActivity?activityId=${id}`, {
      method: 'GET',
      headers: {
        'token': token || ''
      }
    })
    
    const result = await response.json()
    
    if (result.success) {
      enrollments.value = result.data
      volunteers.value = result.volunteers
      error.value = null
    } else {
      throw new Error(result.message || '获取数据失败')
    }
  } catch (err) {
    console.error('获取报名信息失败:', err)
    error.value = '获取报名信息失败: ' + (err instanceof Error ? err.message : '未知错误')
  } finally {
    loading.value = false
  }
}

// 获取活动信息
const fetchActivityInfo = async (id: number) => {
  try {
    const token = localStorage.getItem('token')
    
    const response = await fetch('http://localhost:8080/va/my', {
      method: 'GET',
      headers: {
        'token': token || ''
      }
    })
    
    const result = await response.json()
    
    if (result.success) {
      const activity = result.activities.find((a: Activity) => a.activityId === id)
      if (activity) {
        activityInfo.value = activity
      }
    }
  } catch (err) {
    console.error('获取活动信息失败:', err)
  }
}

// 格式化日期显示
const formatDate = (dateString: string | undefined) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN')
}

// 获取志愿者信息
const getVolunteerInfo = (volunteerId: number) => {
  return volunteers.value[volunteerId.toString()]
}

// 获取状态文本
const getStatusText = (status: number) => {
  switch (status) {
    case 0: return '待审核'
    case 1: return '已通过'
    case 2: return '已拒绝'
    default: return '未知'
  }
}

// 获取状态样式类
const getStatusClass = (status: number) => {
  switch (status) {
    case 0: return 'status-pending'
    case 1: return 'status-approved'
    case 2: return 'status-rejected'
    default: return ''
  }
}

// 通过报名
const approveEnrollment = async (enrollId: number) => {
  if (!confirm('确定要通过此报名吗？')) {
    return
  }
  
  try {
    const token = localStorage.getItem('token')
    
    const response = await fetch(`http://localhost:8080/ve/approve?enrollId=${enrollId}`, {
      method: 'PUT',
      headers: {
        'token': token || '',
        'Content-Type': 'application/json'
      }
    })
    
    const result = await response.json()
    
    if (result.success) {
      // 更新本地状态
      const enrollment = enrollments.value.find(e => e.enrollId === enrollId)
      if (enrollment) {
        enrollment.enrollStatus = 1
      }
      alert('操作成功')
    } else {
      throw new Error(result.message || '操作失败')
    }
  } catch (err) {
    console.error('通过报名失败:', err)
    alert('通过报名失败: ' + (err instanceof Error ? err.message : '未知错误'))
  }
}

// 拒绝报名
const rejectEnrollment = async (enrollId: number) => {
  if (!confirm('确定要拒绝此报名吗？')) {
    return
  }
  
  try {
    const token = localStorage.getItem('token')
    
    const response = await fetch(`http://localhost:8080/ve/reject?enrollId=${enrollId}`, {
      method: 'PUT',
      headers: {
        'token': token || '',
        'Content-Type': 'application/json'
      }
    })
    
    const result = await response.json()
    
    if (result.success) {
      // 更新本地状态
      const enrollment = enrollments.value.find(e => e.enrollId === enrollId)
      if (enrollment) {
        enrollment.enrollStatus = 2
      }
      alert('操作成功')
    } else {
      throw new Error(result.message || '操作失败')
    }
  } catch (err) {
    console.error('拒绝报名失败:', err)
    alert('拒绝报名失败: ' + (err instanceof Error ? err.message : '未知错误'))
  }
}

// 取消通过
const cancelEnrollment = async (enrollId: number) => {
  if (!confirm('确定要取消通过此报名吗？')) {
    return
  }
  
  try {
    const token = localStorage.getItem('token')
    
    const response = await fetch(`http://localhost:8080/ve/cancel?enrollId=${enrollId}`, {
      method: 'PUT',
      headers: {
        'token': token || '',
        'Content-Type': 'application/json'
      }
    })
    
    const result = await response.json()
    
    if (result.success) {
      // 更新本地状态
      const enrollment = enrollments.value.find(e => e.enrollId === enrollId)
      if (enrollment) {
        enrollment.enrollStatus = 0
      }
      alert('操作成功')
    } else {
      throw new Error(result.message || '操作失败')
    }
  } catch (err) {
    console.error('取消通过失败:', err)
    alert('取消通过失败: ' + (err instanceof Error ? err.message : '未知错误'))
  }
}

// 返回活动列表
const goBack = () => {
  // 发送事件到父组件，返回到志愿者活动列表
  window.dispatchEvent(new CustomEvent('showGameEvent', {
    detail: {
      type: 'backToVAList'
    }
  }))
}
</script>

<style scoped>
.ve-container {
  padding: 20px;
  background: none;
  border: none;
  box-shadow: none;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  background: none;
  border: none;
  box-shadow: none;
  padding: 0;
}

.header h2 {
  color: #333;
  margin: 0;
}

.back-button {
  background: linear-gradient(to right, #95a5a6, #7f8c8d);
  color: white;
  border: none;
  border-radius: 8px;
  padding: 10px 20px;
  font-size: 16px;
  cursor: pointer;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.back-button:hover {
  background: linear-gradient(to right, #7f8c8d, #6c7a7b);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
  transform: translateY(-1px);
}

.loading, .error, .no-data {
  text-align: center;
  padding: 40px 20px;
  font-size: 18px;
}

.loading {
  color: #3498db;
}

.error {
  color: #e74c3c;
}

.no-data {
  color: #7f8c8d;
}

.info-section {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  margin-bottom: 30px;
  border-left: 5px solid #3498db;
}

.info-section h3 {
  color: #3498db;
  margin-top: 0;
  border-bottom: 2px solid #eee;
  padding-bottom: 10px;
}

.activity-info p {
  margin: 8px 0;
  color: #555;
}

.enrollments-list h3 {
  color: #333;
  margin: 20px 0;
}

.filter-buttons {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.filters {
  display: flex;
  gap: 10px;
}

.filter-button {
  background: #ecf0f1;
  color: #333;
  border: none;
  border-radius: 5px;
  padding: 8px 15px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.filter-button:hover {
  background: #bdc3c7;
}

.filter-button.active {
  background: #3498db;
  color: white;
}

.table-container {
  overflow-x: auto;
}

.enrollments-table {
  width: 100%;
  border-collapse: collapse;
  background: white;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.enrollments-table th,
.enrollments-table td {
  padding: 12px 15px;
  text-align: left;
  border-bottom: 1px solid #eee;
}

.enrollments-table th {
  background-color: #3498db;
  color: white;
  font-weight: bold;
}

.enrollments-table tr:hover {
  background-color: #f5f5f5;
}

.status-pending {
  color: #f39c12;
  font-weight: bold;
}

.status-approved {
  color: #27ae60;
  font-weight: bold;
}

.status-rejected {
  color: #e74c3c;
  font-weight: bold;
}

.approve-button {
  background: linear-gradient(to right, #27ae60, #2ecc71);
  color: white;
  border: none;
  border-radius: 5px;
  padding: 5px 10px;
  font-size: 14px;
  cursor: pointer;
  margin-right: 5px;
  transition: all 0.3s ease;
}

.approve-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
}

.reject-button {
  background: linear-gradient(to right, #e74c3c, #c0392b);
  color: white;
  border: none;
  border-radius: 5px;
  padding: 5px 10px;
  font-size: 14px;
  cursor: pointer;
  margin-right: 5px;
  transition: all 0.3s ease;
}

.reject-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
}

.cancel-button {
  background: linear-gradient(to right, #f39c12, #d35400);
  color: white;
  border: none;
  border-radius: 5px;
  padding: 5px 10px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.cancel-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
}
</style>